package top.boycharse.blog.dao.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.boycharse.blog.dao.bean.Classify;
import top.boycharse.blog.dao.repository.ClassifyRepository;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class ClassifyService {

    @Autowired
    private ClassifyRepository classifyRepository;

    public List<Classify> getAllClassify(String username) {
        List<Classify> classifyList = classifyRepository.findByUser_userName(username);
        return classifyList;
    }

    /**
     * 保存分类
     * @param classify 分类
     * @return Classify
     */
    @Transactional
    public Classify saveClassify(Classify classify) {
        Classify temp = classifyRepository.save(classify);
        return temp;
    }

    /**
     * 按分类查询
     * @param name 分类名
     * @return Classify
     */
    public Classify findByName(String name) {
        Classify classify = classifyRepository.findByName(name);
        return classify;
    }

    /**
     * 按Id查询
     * @param id
     * @return
     */
    public Classify findById(Integer id) {
        Optional<Classify> classify = classifyRepository.findById(id);
        if (classify.isPresent()) {
            return classify.get();
        }else {
            return null;
        }
    }

    /**
     * 更新标签名
     * @param classify
     * @param name
     */
    @Transactional
    public void update(Classify classify,String name) {
        if (classify == null) {
            return;
        }
        classify.setName(name);
    }

    /**
     * 按Id删除
     * @param id
     */
    public void deleteById(Integer id) {
        classifyRepository.deleteById(id);
    }
}
